#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# :CREATED: [2018-04-26 Thu 21:37]
# :AUTHOR: zb
import paramiko
from untils.untils import log
import threading
from queue import Queue
from models.server import ServerTime, Server
import time, datetime


def ssh2(ip, username, passwd, cmd):
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip, 22, username, passwd, timeout=1)
        stdin, stdout, stderr = ssh.exec_command(cmd)

        o = stdout.read().decode('utf-8')
        e = stderr.read().decode('utf-8')
        ssh.close()
        log('ssh to  {} stdout is : ({})'.format(ip, o), level='debug')
        return o, e
    except Exception as e:
        log('ssh to {} except error {}: \n'.format((ip, username, passwd), e),
            level='error')
        return '', ''


def server_check_time(server):

    cmd = 'date "+%Y-%m-%d %H:%M:%S %Z"'
    s = server
    r, _ = ssh2(s.ip, s.username, s.password, cmd)
    d = {
        'server_id': s.id,
        'server_time': r.strip() or 'check Fail',
        'update_time': datetime.datetime.now(),
    }
    s_t = ServerTime.find_first(server_id=s.id) or ServerTime.new(**d)
    s_t.update(**d)
    ServerTime.insert(s_t).commit()
    log('check {} ,time is:{}'.format(s.ip, r))


def servers_check_time(servers):
    for s in servers:
        log('check {} time start'.format(s.ip))
        server_check_time(s)


def check_by_thread(server):
    """
    Keyword Arguments:
    server -- Server obj
    queue  -- Queue
    """
    t = threading.Thread(target=server_check_time, args=(server))
    t.start()

def sync_server_time(server):
    pass

if __name__ == '__main__':
    pass
